<?php

namespace App\Http\Controllers;

use App\AdminRole;
use App\AdminUser;
use App\User;
use Illuminate\Http\Request;

class AdminUserController extends Controller
{
    //
    public function ulist()
    {
        $adminUsers = AdminUser::all();
        return view("admin.user.list",compact("adminUsers"));
    }
    public function add()
    {
        return view("admin.user.add");
    }
    public function store(Request $request,AdminUser $adminUser)
    {
        $this->validate($request,[
            'name'=>'required|max:20|min:3',
            'password'=> 'required|max:20|min:3|confirmed',
        ]);
        $adminUser->name = $request->name;
        $adminUser->password = bcrypt($request->password);
        if ($adminUser->save()){
            return [
                "error"=>0,
                "info"=>"添加成功",
            ];
        }

    }
    public function role(AdminUser $adminUser)
    {
        $myRoles = $adminUser->role;
        $adminRoles = AdminRole::all();
        return view("admin.user.edit",compact("adminUser","adminRoles","myRoles"));

    }

    public function roleStore(Request $request, AdminUser $adminUser)
    {
        $newRoles = AdminRole::find($request->role_id);
        $myRoles = $adminUser->role;
        $addRoles = $newRoles->diff($myRoles);
        $delRoles = $myRoles ->diff($newRoles);
        foreach ($addRoles as $addRole){
            $adminUser->assignRole($addRole);
        }
        foreach ($delRoles as $delRole){
            $adminUser->delRole($delRole);
        }
        return [
            "error"=>0,
            "info"=>"编辑成功",
        ];
    }
}
